const router = require('express').Router()
const uploader = require('../controller/upload')
const fs =require('fs')
const auth = require('../middleware/auth')
const jwt = require('jsonwebtoken')
const config = require('../config')
//文件上传功能
const multer = require('multer')
const{checkFileSuffix} = require('../utils')
//获取上传用户ID
//控制文件上传位置

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        let token = req.headers.authorization
        let spaceIndex = token.indexOf(' ')
        token = token.substring(spaceIndex + 1,token.length)
        token =  jwt.verify(token,config.secret)
        const userId = token._id
        let dir = 'public/uploads/'+userId
        if(!fs.existsSync(dir)){
            fs.mkdirSync(dir, {recursive: true})
        }
        cb(null, dir)
    },
    filename: function (req, file, cb) {
        let oname = file.originalname
        let pointIndex = oname.lastIndexOf('.')
        let suffix = oname.substring(pointIndex + 1,oname.length)
        if (checkFileSuffix(suffix.toLowerCase())){
            cb(null, file.fieldname + '-' + Date.now()+'.'+suffix)
        } else{
            // 不符合规则，拒绝文件并且直接抛出错误
            cb(new Error('文件类型错误'));
          }
    }
})
// console.log(token)
const upload = multer({ storage: storage })

//帖子上传图片
router.post('/', [upload.single("topicImg"),auth], uploader.uploadFile)

module.exports = router